<template>
  <div class="system-monitoring">
    <!-- 页面头部导航 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          type="primary" 
          icon="ArrowLeft" 
          @click="$router.back()"
          class="back-btn"
        >
          返回
        </el-button>
        <div class="page-info">
          <h2>系统监控</h2>
          <p>监控系统运行状态和基础统计信息</p>
        </div>
      </div>
      
      <div class="header-right">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="navigateToHome" class="breadcrumb-link">控制台</el-breadcrumb-item>
          <el-breadcrumb-item>系统监控</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <!-- 系统统计卡片 -->
    <div class="stats-grid">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon size="32" color="#67c23a">
              <Shop />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ systemStats?.shopStats.totalCount || 0 }}</div>
            <div class="stat-label">总店铺数</div>
          </div>
        </div>
        <div class="stat-detail">
          <span class="detail-item success">运营中: {{ systemStats?.shopStats.activeCount || 0 }}</span>
          <span class="detail-item warning">暂停: {{ systemStats?.shopStats.suspendedCount || 0 }}</span>
          <span class="detail-item danger">关闭: {{ systemStats?.shopStats.closedCount || 0 }}</span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon size="32" color="#409eff">
              <User />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ systemStats?.userStats.totalUsers || 0 }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </div>
        <div class="stat-detail">
          <span class="detail-item info">管理员: {{ systemStats?.userStats.superAdminCount || 0 }}</span>
          <span class="detail-item primary">店长: {{ systemStats?.userStats.managerCount || 0 }}</span>
          <span class="detail-item success">打手: {{ systemStats?.userStats.workerCount || 0 }}</span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon size="32" color="#e6a23c">
              <Monitor />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ systemUptime }}</div>
            <div class="stat-label">系统运行时间</div>
          </div>
        </div>
        <div class="stat-detail">
          <span class="detail-item info">版本: {{ systemStats?.systemStatus.version || 'v1.0.0' }}</span>
          <span class="detail-item success">数据库: {{ systemStats?.systemStatus.databaseStatus || '未知' }}</span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon size="32" color="#f56c6c">
              <Cpu />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ memoryUsage }}%</div>
            <div class="stat-label">内存使用率</div>
          </div>
        </div>
        <div class="stat-detail">
          <span class="detail-item info">已用: {{ usedMemory }}MB</span>
          <span class="detail-item primary">总计: {{ totalMemory }}MB</span>
        </div>
      </el-card>
    </div>

    <!-- 详细信息区域 -->
    <div class="detail-section">
      <div class="detail-left">
        <!-- 店铺状态分布 -->
        <el-card title="店铺状态分布" shadow="never">
          <template #header>
            <div class="card-header">
              <span>店铺状态分布</span>
              <el-button 
                type="text" 
                icon="Refresh" 
                @click="refreshShopStats"
                :loading="shopStatsLoading"
              >
                刷新
              </el-button>
            </div>
          </template>
          
          <div v-loading="shopStatsLoading" class="chart-container">
            <div class="status-list">
              <div class="status-item" v-for="(value, key) in shopStats?.statusDistribution" :key="key">
                <div class="status-dot" :class="getStatusClass(key)"></div>
                <span class="status-name">{{ getStatusName(key) }}</span>
                <span class="status-count">{{ value }}</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 用户角色分布 -->
        <el-card title="用户角色分布" shadow="never" style="margin-top: 16px;">
          <template #header>
            <div class="card-header">
              <span>用户角色分布</span>
              <el-button 
                type="text" 
                icon="Refresh" 
                @click="refreshUserStats"
                :loading="userStatsLoading"
              >
                刷新
              </el-button>
            </div>
          </template>
          
          <div v-loading="userStatsLoading" class="chart-container">
            <div class="role-list">
              <div class="role-item" v-for="(value, key) in userStats?.roleDistribution" :key="key">
                <div class="role-dot" :class="getRoleClass(key)"></div>
                <span class="role-name">{{ getRoleName(key) }}</span>
                <span class="role-count">{{ value }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <div class="detail-right">
        <!-- 系统运行状态 -->
        <el-card title="系统运行状态" shadow="never">
          <template #header>
            <div class="card-header">
              <span>系统运行状态</span>
              <el-button 
                type="text" 
                icon="Refresh" 
                @click="refreshSystemStatus"
                :loading="systemStatusLoading"
              >
                刷新
              </el-button>
            </div>
          </template>
          
          <div v-loading="systemStatusLoading" class="system-info">
            <div class="info-item">
              <span class="info-label">系统版本:</span>
              <span class="info-value">{{ systemStatus?.version || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">启动时间:</span>
              <span class="info-value">{{ formatTime(systemStatus?.startTime) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">运行时间:</span>
              <span class="info-value">{{ formatUptime(systemStatus?.uptime) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">Java版本:</span>
              <span class="info-value">{{ systemStatus?.jvmInfo.javaVersion || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">JVM名称:</span>
              <span class="info-value">{{ systemStatus?.jvmInfo.jvmName || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">数据库状态:</span>
              <el-tag 
                :type="systemStatus?.databaseStatus === 'connected' ? 'success' : 'danger'"
                size="small"
              >
                {{ systemStatus?.databaseStatus === 'connected' ? '已连接' : '未连接' }}
              </el-tag>
            </div>
          </div>
        </el-card>

        <!-- 健康检查 -->
        <el-card title="健康检查" shadow="never" style="margin-top: 16px;">
          <template #header>
            <div class="card-header">
              <span>健康检查</span>
              <el-button 
                type="text" 
                icon="Refresh" 
                @click="refreshHealthCheck"
                :loading="healthLoading"
              >
                检查
              </el-button>
            </div>
          </template>
          
          <div v-loading="healthLoading" class="health-info">
            <div class="health-item">
              <span class="health-label">整体健康:</span>
              <el-tag 
                :type="healthCheck?.overallHealth ? 'success' : 'danger'"
                size="small"
              >
                {{ healthCheck?.overallHealth ? '健康' : '异常' }}
              </el-tag>
            </div>
            <div class="health-item">
              <span class="health-label">数据库健康:</span>
              <el-tag 
                :type="healthCheck?.databaseHealth ? 'success' : 'danger'"
                size="small"
              >
                {{ healthCheck?.databaseHealth ? '正常' : '异常' }}
              </el-tag>
            </div>
            <div class="health-item">
              <span class="health-label">内存健康:</span>
              <el-tag 
                :type="healthCheck?.memoryHealth ? 'success' : 'warning'"
                size="small"
              >
                {{ healthCheck?.memoryHealth ? '正常' : '警告' }}
              </el-tag>
            </div>
            <div class="health-item">
              <span class="health-label">系统健康:</span>
              <el-tag 
                :type="healthCheck?.systemHealth ? 'success' : 'danger'"
                size="small"
              >
                {{ healthCheck?.systemHealth ? '正常' : '异常' }}
              </el-tag>
            </div>
            <div class="health-item">
              <span class="health-label">运行时间:</span>
              <span class="health-value">{{ healthCheck?.uptimeMinutes || 0 }} 分钟</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 操作工具栏 -->
    <div class="action-toolbar">
      <el-button 
        type="primary" 
        icon="Refresh" 
        @click="refreshAllData"
        :loading="loading"
      >
        刷新所有数据
      </el-button>
      
      <el-button 
        type="success" 
        icon="Check" 
        @click="refreshHealthCheck"
        :loading="healthLoading"
      >
        健康检查
      </el-button>
      
      <el-button 
        type="info" 
        icon="Connection" 
        @click="checkDatabaseStatus"
        :loading="databaseLoading"
      >
        检查数据库
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Shop, User, Monitor, Cpu } from '@element-plus/icons-vue'

const router = useRouter()
import { 
  adminSystemApi, 
  type SystemStats, 
  type ShopStats, 
  type UserStats, 
  type SystemStatus,
  type HealthCheck 
} from '@renderer/api/admin'

// 响应式数据
const loading = ref(false)
const shopStatsLoading = ref(false)
const userStatsLoading = ref(false)
const systemStatusLoading = ref(false)
const healthLoading = ref(false)
const databaseLoading = ref(false)

const systemStats = ref<SystemStats | null>(null)
const shopStats = ref<ShopStats | null>(null)
const userStats = ref<UserStats | null>(null)
const systemStatus = ref<SystemStatus | null>(null)
const healthCheck = ref<HealthCheck | null>(null)

// 计算属性
const systemUptime = computed(() => {
  if (!systemStats.value?.systemStatus.uptime) return '0天'
  return formatUptime(systemStats.value.systemStatus.uptime)
})

const memoryUsage = computed(() => {
  if (!systemStats.value?.systemStatus.jvmInfo.memoryUsage) return 0
  return Math.round(systemStats.value.systemStatus.jvmInfo.memoryUsage)
})

const usedMemory = computed(() => {
  if (!systemStats.value?.systemStatus.jvmInfo.usedMemory) return 0
  return systemStats.value.systemStatus.jvmInfo.usedMemory
})

const totalMemory = computed(() => {
  if (!systemStats.value?.systemStatus.jvmInfo.totalMemory) return 0
  return systemStats.value.systemStatus.jvmInfo.totalMemory
})

// 加载系统整体统计数据
const loadSystemStats = async () => {
  try {
    loading.value = true
    const response = await adminSystemApi.getSystemStats()
    systemStats.value = response.data.data
  } catch (error) {
    console.error('加载系统统计数据失败:', error)
    ElMessage.error('加载系统统计数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新店铺统计数据
const refreshShopStats = async () => {
  try {
    shopStatsLoading.value = true
    const response = await adminSystemApi.getShopStats()
    shopStats.value = response.data.data
  } catch (error) {
    console.error('刷新店铺统计数据失败:', error)
    ElMessage.error('刷新店铺统计数据失败')
  } finally {
    shopStatsLoading.value = false
  }
}

// 刷新用户统计数据
const refreshUserStats = async () => {
  try {
    userStatsLoading.value = true
    const response = await adminSystemApi.getUserStats()
    userStats.value = response.data.data
  } catch (error) {
    console.error('刷新用户统计数据失败:', error)
    ElMessage.error('刷新用户统计数据失败')
  } finally {
    userStatsLoading.value = false
  }
}

// 刷新系统运行状态
const refreshSystemStatus = async () => {
  try {
    systemStatusLoading.value = true
    const response = await adminSystemApi.getSystemStatus()
    systemStatus.value = response.data.data
  } catch (error) {
    console.error('刷新系统状态失败:', error)
    ElMessage.error('刷新系统状态失败')
  } finally {
    systemStatusLoading.value = false
  }
}

// 刷新健康检查
const refreshHealthCheck = async () => {
  try {
    healthLoading.value = true
    const response = await adminSystemApi.getHealthCheck()
    healthCheck.value = response.data.data
    
    if (healthCheck.value.overallHealth) {
      ElMessage.success('系统健康状态良好')
    } else {
      ElMessage.warning('系统健康状态存在问题，请检查详细信息')
    }
  } catch (error) {
    console.error('健康检查失败:', error)
    ElMessage.error('健康检查失败')
  } finally {
    healthLoading.value = false
  }
}

// 检查数据库状态
const checkDatabaseStatus = async () => {
  try {
    databaseLoading.value = true
    const response = await adminSystemApi.getDatabaseStatus()
    const status = response.data.data
    
    if (status === 'connected') {
      ElMessage.success('数据库连接正常')
    } else {
      ElMessage.error('数据库连接异常')
    }
  } catch (error) {
    console.error('检查数据库状态失败:', error)
    ElMessage.error('检查数据库状态失败')
  } finally {
    databaseLoading.value = false
  }
}

// 刷新所有数据
const refreshAllData = async () => {
  await Promise.all([
    loadSystemStats(),
    refreshShopStats(),
    refreshUserStats(),
    refreshSystemStatus()
  ])
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  const classes: Record<string, string> = {
    'active': 'status-success',
    'suspended': 'status-warning',
    'closed': 'status-danger'
  }
  return classes[status] || 'status-info'
}

// 获取状态名称
const getStatusName = (status: string) => {
  const names: Record<string, string> = {
    'active': '运营中',
    'suspended': '已暂停',
    'closed': '已关闭'
  }
  return names[status] || '未知'
}

// 获取角色样式类
const getRoleClass = (role: string) => {
  const classes: Record<string, string> = {
    'super_admin': 'role-info',
    'manager': 'role-primary',
    'worker': 'role-success'
  }
  return classes[role] || 'role-default'
}

// 获取角色名称
const getRoleName = (role: string) => {
  const names: Record<string, string> = {
    'super_admin': '超级管理员',
    'manager': '店长',
    'worker': '打手'
  }
  return names[role] || '未知'
}

// 格式化时间
const formatTime = (timeStr: string | undefined) => {
  if (!timeStr) return '-'
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 格式化运行时间
const formatUptime = (uptime: number | undefined) => {
  if (!uptime) return '0天'
  
  const days = Math.floor(uptime / (24 * 60 * 60 * 1000))
  const hours = Math.floor((uptime % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000))
  const minutes = Math.floor((uptime % (60 * 60 * 1000)) / (60 * 1000))
  
  if (days > 0) {
    return `${days}天${hours}小时`
  } else if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 导航到首页
const navigateToHome = () => {
  router.push('/admin/dashboard')
}

// 页面加载
onMounted(() => {
  refreshAllData()
})
</script>

<style scoped lang="scss">
.system-monitoring {
  padding: 20px;
  
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    padding: 16px 24px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      .back-btn {
        border-radius: 8px;
        
        &:hover {
          transform: translateY(-1px);
        }
      }
      
      .page-info {
        h2 {
          margin: 0 0 4px 0;
          font-size: 24px;
          font-weight: 600;
          color: #303133;
        }
        
        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }
    }
    
    .header-right {
      .breadcrumb-link {
        cursor: pointer;
        color: #409eff;
        
        &:hover {
          color: #66b1ff;
        }
      }
    }
  }
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 24px;
    
    @media (max-width: 1200px) {
      grid-template-columns: repeat(2, 1fr);
    }
    
    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
  }
  
  .stat-card {
    .stat-content {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      
      .stat-icon {
        margin-right: 12px;
      }
      
      .stat-info {
        .stat-number {
          font-size: 32px;
          font-weight: 700;
          color: #303133;
          line-height: 1;
        }
        
        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-top: 4px;
        }
      }
    }
    
    .stat-detail {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;
      
      .detail-item {
        font-size: 12px;
        padding: 2px 6px;
        border-radius: 4px;
        background: #f0f2f5;
        color: #606266;
        
        &.success { background: #f0f9ff; color: #67c23a; }
        &.warning { background: #fdf6ec; color: #e6a23c; }
        &.danger { background: #fef0f0; color: #f56c6c; }
        &.info { background: #f4f4f5; color: #909399; }
        &.primary { background: #ecf5ff; color: #409eff; }
      }
    }
  }
  
  .detail-section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-bottom: 24px;
    
    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .chart-container {
    min-height: 120px;
  }
  
  .status-list, .role-list {
    .status-item, .role-item {
      display: flex;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .status-dot, .role-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin-right: 12px;
        
        &.status-success, &.role-success { background: #67c23a; }
        &.status-warning { background: #e6a23c; }
        &.status-danger { background: #f56c6c; }
        &.status-info, &.role-info { background: #909399; }
        &.role-primary { background: #409eff; }
        &.role-default { background: #ddd; }
      }
      
      .status-name, .role-name {
        flex: 1;
        font-size: 14px;
        color: #606266;
      }
      
      .status-count, .role-count {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }
  }
  
  .system-info, .health-info {
    .info-item, .health-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .info-label, .health-label {
        font-size: 14px;
        color: #909399;
      }
      
      .info-value, .health-value {
        font-size: 14px;
        color: #303133;
        font-weight: 500;
      }
    }
  }
  
  .action-toolbar {
    display: flex;
    gap: 12px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;
  }
}

.el-card {
  margin-bottom: 0;
}
</style>